//
//  WLNetworkTools.swift
//  weibo
//
//  Created by 刁 海瑞 on 16/8/10.
//  Copyright © 2016年 毋磊. All rights reserved.
//

import UIKit
import AFNetworking
//网络请求枚举值
enum RequestType: Int {
    
    case GET = 0
    
    case POST = 1
    
}

class WLNetworkTools: AFHTTPSessionManager {
    
//    单例全局访问
    static let sharedTools: WLNetworkTools = {
       
        let tools = WLNetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
//    封装GET和POST请求
    func request(requestType: RequestType, url: String,params: AnyObject?, callBack: (response: AnyObject?, error: NSError?)->()){
    
        if requestType == .GET{
            
            GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                
                callBack(response: response, error: nil)
                
                }, failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)
            })
        }else{
            
           POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
            callBack(response: response, error: nil)
            }, failure: { (_, error) -> Void in
                callBack(response: nil, error: error)
           })
        }
    
    }
}

extension WLNetworkTools{
    
//    通过code获取accesstoken
    func reqeustAccessTokenWithCode(code: String, callBack: (response: AnyObject?, error: NSError?)->()){
//        准备url
        let url = "https://api.weibo.com/oauth2/access_token"
//        准备参数
        let params = [
        
        "client_id": WeiboAppKey,
        "client_secret": WeiboAppSecret,
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": WeiboAppRedirect_Uri
        ]
        
        request(.POST, url: url, params: params, callBack: callBack)
        
    }
    
    //   通过accesstoken和uid获取用户信息
    func requestUserInfo(userAccount: WLUserAccount, callBack: (response: AnyObject?, error: NSError?)->()){
        //        准备url
        let url = "https://api.weibo.com/2/users/show.json"
        //        准备参数
        let params = [
            
            "access_token": userAccount.access_token!,
            "uid":"\(userAccount.uid)"
            
        ]
//     执行请求
        request(.GET, url: url, params: params, callBack: callBack)
    }
}
